import json
import os
from idlelib.iomenu import encoding


def change_to_new_count(p_path: str, new_count: int):
    ts_path = os.path.join(p_path, 'src/resources/dictionary.ts')
    with open(ts_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    new_lines = []
    for line in lines:
        if '// replace' in line:
            new_lines.append(f"    length: {new_count}, // replace\n")
        else:
            new_lines.append(line)
    with open(ts_path, 'w', encoding='utf-8') as file:
        file.writelines(new_lines)

def append_word_txt(p_path: str, new_words_path: str):
    p = os.path.join(p_path, 'public/dicts/2025KaoYanHongBaoShu.json')
    res = json.loads(open(p, 'r', encoding='utf-8').read())
    words_map = {}
    for w in res:
        words_map[w['name']] = w

    words_txt = json.loads(open(os.path.join(p_path, new_words_path), encoding='utf-8').read())

    match_words = []
    for w in words_txt:
        if w in words_map:
            match_words.append(words_map[w])

    custom_path = os.path.join(p_path, 'public/dicts/custom.json')
    if not os.path.exists(custom_path):
        open(custom_path, 'w', encoding='utf-8').write('[]')
    all_words = json.loads(open(custom_path, 'r', encoding='utf-8').read())

    all_words_map = {}
    for w in all_words:
        all_words_map[w['name']] = w

    for w in match_words:
        if w['name'] not in all_words_map:
            all_words_map[w['name']] = w

    # all_words.extend(match_words)
    all_words = list(all_words_map.values())

    open(custom_path, 'w', encoding='utf-8').write(json.dumps(all_words, ensure_ascii=False, indent=2))
    print(len(all_words))

    change_to_new_count(p_path, len(all_words))

project_path = '/Users/ruby/Code/qwerty-learner/'
import os
if os.name == 'nt':
    project_path = 'C:/Users/ruby/code/qwerty-learner/'

append_word_txt(project_path, 'dev-docs/words/26.txt')
